/*
 * Copyright (C), 2015-2019
 * FileName: BaseConstantInfo
 * Author:   lizhao
 * Date:     2019-02-11 12:33
 * Description: 常量池的通用类
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.lizhaoblog.jjvm.classfile.constantpool;

import com.lizhaoblog.jjvm.common.CommonValue;
import com.lizhaoblog.jjvm.classfile.ClassReader;
import com.lizhaoblog.jjvm.classfile.constantpool.impl.*;

/**
 * 〈一句话功能简述〉<br>
 * 〈常量池的通用类〉
 *
 * @author lizhao
 * @date 2019-02-11 12:33
 * @since 1.0.0
 */
public abstract class BaseConstantInfo implements ConstantInfo {
    protected String value;

    @Override
    public String getValue() {
        return value;
    }

    public String toString() {
        return getValue();
    }

    // 工厂方法
    public static ConstantInfo createConstantInfo(int tag, ClassReader reader, ConstantPool constantPool) {
        switch (tag) {
            case CommonValue.CONSTANT_POOL_TAG_UTF8:
                return new ConstantInfoUft8(reader);

            // 数字
            case CommonValue.CONSTANT_POOL_TAG_INTEGER:
                return new ConstantInfoInteger(reader);
            case CommonValue.CONSTANT_POOL_TAG_FLOAT:
                return new ConstantInfoFloat(reader);
            case CommonValue.CONSTANT_POOL_TAG_LONG:
                return new ConstantInfoLong(reader);
            case CommonValue.CONSTANT_POOL_TAG_DOUBLE:
                return new ConstantInfoDouble(reader);

            // 以下3个引用UTF8
            case CommonValue.CONSTANT_POOL_TAG_STRING:
                return new ConstantInfoString(constantPool, reader);
            case CommonValue.CONSTANT_POOL_TAG_CLASS:
                return new ConstantInfoClass(constantPool, reader);
            case CommonValue.CONSTANT_POOL_TAG_NAME_AND_TYPE:
                return new ConstantInfoNameAndType(constantPool, reader);

            // 以下3个引用CLASS+NAME_AND_TYPE
            case CommonValue.CONSTANT_POOL_TAG_FIELD_REF:
                return new ConstantInfoFieldref(constantPool, reader);
            case CommonValue.CONSTANT_POOL_TAG_METHOD_REF:
                return new ConstantInfoMethodref(constantPool, reader);
            case CommonValue.CONSTANT_POOL_TAG_INTERFACE_METHOD_REF:
                return new ConstantInfoNameAndType(constantPool, reader);

            // 是Java SE 7才添加到class文件中的，目的是支持新增的invokedynamic指令
            case CommonValue.CONSTANT_POOL_TAG_METHOD_HANDLE:
                return new ConstantInfoMethodHandle(constantPool, reader);
            case CommonValue.CONSTANT_POOL_TAG_METHOD_TYPE:
                return new ConstantInfoMethodType(constantPool, reader);
            case CommonValue.CONSTANT_POOL_TAG_INVOKE_DYNAMIC:
                return new ConstantInfoInvokeDynamic(constantPool, reader);

            default:
                throw new ClassFormatError("constant pool tag!");
        }
    }
}
